package com.fagp.register.controller;

import com.fagp.mew.common.rest.login.ForcedOfflineRequest;
import com.zebra.common.OnlineType;
import com.zebra.common.ServerBriefInfo;
import com.zebra.common.ZbmMessage;
import com.zebra.register.LoadBalanceService;
import com.zebra.register.RegisterSendMessageUtil;
import com.zebra.remoting.config.BasisCommandCode;
import com.zebra.remoting.config.EmptyMessage;
import com.zebra.remoting.config.TmsServerInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;


@RestController
@Slf4j
public class RegisterProvideController {


    @Autowired
    private LoadBalanceService loadBalanceService;

    /**
     *  获取 Gateway 信息
     * @return
     */
    @GetMapping(value = "/get/gateway")
    @ResponseBody
    public ServerBriefInfo getGateway(){
        ServerBriefInfo serverBriefInfo = loadBalanceService.loadGateway();
        log.info("GW load balance {}", serverBriefInfo);
        return serverBriefInfo;
    }


    @PostMapping(value = "/offline/forced")
    @ResponseBody
    public Integer forcedOffline(@RequestBody ForcedOfflineRequest request){
        log.info("User forced offline  {}",  request.toString());
        if (null == request){
            log.error("offline-forced: request is null");
            return 0;
        }

        log.info("offline-forced: {}", request);
        RegisterSendMessageUtil.pushGw(request.getGatewaySid(),
                BasisCommandCode.REPEAT_LOGIN.cmd(),
                request.getUserId(), request.getToken(), new EmptyMessage());
        return 1;
    }

    @PostMapping(value = "/zbm/common")
    @ResponseBody
    public Integer zbmCommon(@RequestBody ZbmMessage request){
        log.info("ZBM  {}",  request.toString());
        if (null == request){
            log.error("zbm-common: request is null");
            return 0;
        }
        log.info("zbm-common: {}", request);
        RegisterSendMessageUtil.pushGwAll(BasisCommandCode.ZBM.cmd(), request);
        return 1;
    }

    @PostMapping(value = "/pushgold/{uid}/{gnum}/{tmsid}")
    @ResponseBody
    public Integer pushGoldToTMS(@PathVariable("uid") long uid, @PathVariable("gnum") long gnum, @PathVariable("tmsid") int tmsid){
        log.info("Push gold TMS uid: {}, gnum {}, tmsid {}", uid, gnum, tmsid);
        loadBalanceService.sendTMSGoldPush(uid, gnum, (byte) 0, tmsid);
        return 1;
    }


    @GetMapping(value = "/tms/online/{serverid}/{online}")
    @ResponseBody
    public String updateTmsOnline(@PathVariable("serverid") int serverid, @PathVariable("online") int online){
        log.info("Update Tms Online, tmsId: {}, onlineType {}", serverid, online);
        OnlineType onlineType = OnlineType.valueOf(online);
        if (null == onlineType){
            return "OnlineType illegal online: "+online;
        }

        try {
            loadBalanceService.updateTMSOnlineState(serverid, online);
            return "SUCCESS";
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return e.getMessage();
        }
    }

    @GetMapping(value = "/tms/online/all/{online}")
    @ResponseBody
    public String updateTmsOnlineALL(@PathVariable("online") int online){
        log.info("Update Tms ALL Online,  onlineType {}",  online);
        OnlineType onlineType = OnlineType.valueOf(online);
        if (null == onlineType){
            return "OnlineType illegal online: "+online;
        }
        List<TmsServerInfo> list = loadBalanceService.findTmsByAll();
        if (null == list || list.isEmpty()){
            return "TMS list is null";
        }
        try {
            for(TmsServerInfo tms : list){
               loadBalanceService.updateTMSOnlineState(tms.getServerId(), online);
            }
            return "SUCCESS";
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return e.getMessage();
        }
    }

    @GetMapping(value = "/tms/state/{serverid}")
    @ResponseBody
    public Integer getTmsState(@PathVariable("serverid") int serverid){
        log.info("Get  Tms state,  tmsId {}",  serverid);
        return Optional.ofNullable(loadBalanceService.getTmsBySid(serverid)).map(TmsServerInfo::getOnline).orElse(-1);
    }

}
